<?php

define("WP_CL_DBPREFIX", "cache-lite_");

function cl_activated() {
	add_option(WP_CL_DBPREFIX."tposted", time());
	add_option(WP_CL_DBPREFIX."tgened", time());
}

function cl_deactivated() {
	delete_option(WP_CL_DBPREFIX."tposted", time());
	delete_option(WP_CL_DBPREFIX."tgened", time());
}

function cl_posted_hook($q) {
	$myq = strtolower($q);
	if(strpos($myq, "select")!==false)	return $q;
	if(strpos($myq, WP_CL_DBPREFIX)!==false)	return $q;

	if(
	strpos($myq, "insert")!==false
	|| strpos($myq, "update")!==false
	|| strpos($myq, "delete")!==false ) {
		update_option(WP_CL_DBPREFIX."tposted", time());
	}
	return $q;
}

add_filter("query", "cl_posted_hook");

function cl_remove($file) {
	if (is_dir($file) && !is_link($file)) {
		foreach(glob($file.'/*') as $f) {
			cl_remove($f);
		}
		return rmdir($file);
	} else {
		return unlink($file);
	}
}

function _cl_handle_file($file, $iswin=false) {
	require(dirname(__FILE__).'/settings.php');

	$tnow = get_option(WP_CL_DBPREFIX."tposted");
	$tgened = get_option(WP_CL_DBPREFIX."tgened");

	$create = false;

	if(($tgened < $tnow)) {
		cl_remove(WP_CL_DIR."$tgened/");
		update_option(WP_CL_DBPREFIX."tgened", $tnow);
		$tgened = $tnow;
		$create = true;
	}

	$cached_file = str_replace(ABSPATH, WP_CL_DIR."$tgened/", $file);
	if($iswin)	$cached_file = str_replace("/", "\\", $cached_file);		//FOR WINDOWS USERS -- uncomment this line
	$cached_file = str_replace(basename($cached_file), md5(serialize($GLOBALS["wp_query"])).".".basename($cached_file), $cached_file);

	if(!file_exists($cached_file)) {
		$create = true;
	}

	if($create) {
		global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;

		ob_start();
		require_once($file);
		@mkdir(dirname($cached_file), 0777, true);
		file_put_contents($cached_file, ob_get_contents());
		ob_end_flush();
	} else {
		echo(file_get_contents($cached_file));
	}
}

?>